package com.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

import com.dao.UserDao;
import com.model.UserVO;

public class UserDaoImpl implements UserDao {
	private JdbcTemplate jdbcTemplate;

	public List find() {
		String sql = "select * from user";
		return jdbcTemplate.query(sql, new UserMapper());
	}

	/*
	 * 因为query方法不能直接放回一个数组，所以我们只能通过rowMapper赋值给uservo;
	 * RowMapper可以将数据中的每一行封装成用户定义的类，在数据库查询中，如果返回的类型是用户自定义的类型则需要包装
	 */
	private static final class UserMapper implements RowMapper {
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			UserVO uservo = new UserVO();
			uservo.setId(rs.getInt("id"));
			uservo.setName(rs.getString("name"));
			uservo.setPwd(rs.getString("pwd"));
			return uservo;
		}
	}

	public void insert(UserVO uservo) {
		String sql = " insert into user (name,pwd) values(?,?)";
		jdbcTemplate.update(sql,
				new Object[] { uservo.getName(), uservo.getPwd() });
	}

	public void delete(int id) {
		String sql = "delete from user where id=?";
		jdbcTemplate.update(sql, id);
	}

	public void update(UserVO uservo) {
		String sql = "update user set name=?,pwd=? where id=?";
		jdbcTemplate.update(sql, uservo.getName(), uservo.getPwd(),
				uservo.getId());
	}

	public UserVO select(int id) {
		String sql = "select * from user where id=?";
		return jdbcTemplate.queryForObject(sql,
				ParameterizedBeanPropertyRowMapper.newInstance(UserVO.class),
				id);

	}

	public UserVO selectByName(String name, String pwd) {
		String sql = "select * from user where name=? and pwd=?";
		try {
			return jdbcTemplate.queryForObject(sql,
					ParameterizedBeanPropertyRowMapper
							.newInstance(UserVO.class), name, pwd);
		} catch (Exception e) {
			return null;
		}
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

}
